<?php

namespace Trawind\Helpers;

class TransformerHelper
{
    /**
     * @var string[]
     */
    static $validParams = ['limit', 'order'];

    /**
     * filter the null by model
     * @param $transformer
     * @param $model
     */
    public static function parseFieldsets($transformer, $model)
    {
        $currentScope = $transformer->getCurrentScope();
        $resourceKey = $currentScope->getResource()->getResourceKey();
        $manager = $currentScope->getManager();
        $showData = $model->toArray();
        $showFields = array_keys($showData);
        if ($transformer->fieldTranslations && is_array($transformer->fieldTranslations)) {
            foreach ($transformer->fieldTranslations as $key => $val) {
                if (isset($showData[$key])) {
                    $showFields[] = $val;
                } else {
                    $showFields = array_diff($showFields, array($val));
                }
            }
        }
        $fieldSet = [
            $resourceKey => $showFields
        ];
        if ($requestFieldSet = $manager->getRequestedFieldsets()) {
            $fieldSet = array_merge($fieldSet, $requestFieldSet);
        }
        $manager->parseFieldsets($fieldSet);
    }

    /**
     * @param $params
     * @param $model
     * @return mixed
     * @throws \Exception
     */
    public static function filterModel($params, $model)
    {
        if ($params !== null) {
            // Optional params validation
            $usedParams = array_keys(iterator_to_array($params));
            if ($invalidParams = array_diff($usedParams, self::$validParams)) {
                throw new \Exception(sprintf(
                    'Invalid param(s): "%s". Valid param(s): "%s"',
                    implode(',', $usedParams),
                    implode(',', self::$validParams)
                ));
            }

            // Processing
            list($limit, $offset) = $params->get('limit');
            list($orderCol, $orderBy) = $params->get('order');
            if ($model->toArray()) {
                if (strtolower($orderBy) == 'desc') {
                    $model = $model->sortByDesc($orderCol);
                } elseif (strtolower($orderBy) == 'asc'){
                    $model = $model->sortBy($orderCol);
                }
                $model = $model->slice($offset, $limit);
                $model = $model->all();
            }
            return $model;
        }
    }
}